/**
 * 帆布指纹识别技术。它是一种利用帆布纹理特征进行身份验证的方法。
 * 具体实现的思路，就是利用 HTML5 的画布的 Canvas 特性，通过 Canvas 生成的图片，然后转换成哈希码，从而形成用户指纹。
 */
type FingerprintOptions = {
  font?: string;
  reactStyle?: string | CanvasGradient | CanvasPattern;
  contentStyle?: string | CanvasGradient | CanvasPattern;
  textBaseline?: CanvasTextBaseline;
  content?: string;
};
export function getFingerprintId(content: string, options?: FingerprintOptions): string | undefined;
export function getFingerprintId(options: FingerprintOptions): string | undefined;
export function getFingerprintId(...args: any[]): string | undefined {
  let txt = "log-sdk";
  let [content, options] = args;

  if (typeof content === "object") {
    txt = content.content || txt;
    options = content;
  }

  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return void 0;

  ctx.textBaseline = options?.textBaseline ?? "top";
  ctx.font = options?.font ?? "14px 'Arial'";
  ctx.fillStyle = options?.reactStyle ?? "#f60";
  // 先画一个100x20矩形内容
  ctx.fillRect(10, 10, 100, 20);
  ctx.fillStyle = options?.contentStyle ?? "#069";
  // 把字填充到矩形内
  ctx.fillText(txt, 2, 15);
  const b64 = canvas.toDataURL().replace("data:image/png;base64,", "");
  const bin = globalThis.atob(b64);
  const crc = bin2hex(bin.slice(-16, -12));
  return crc;
}

export const bin2hex = (str: string) => {
  let o = "";
  let n = null;
  str += "";
  for (let i = 0, l = str.length; i < l; i++) {
    n = str.charCodeAt(i).toString(16);
    o += n.length < 2 ? "0" + n : n;
  }

  return o;
};
